package com.byl.qrobot.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.byl.qrobot.R;
import com.byl.qrobot.util.HttpUtil;
import com.byl.qrobot.util.LogUtil;
import com.byl.qrobot.util.SysUtils;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.tsz.afinal.http.AjaxParams;

public class LoginActivity extends Activity  implements OnClickListener{
    private TextView mBtnLogin,main_btn_register,getpassword;
    public EditText email,password;
    private View progress;
    private View mInputLayout;
    private float mWidth, mHeight;
    private LinearLayout mName, mPsw;

    //提示框
    public ProgressDialog dialog;

    //服务器返回的数据
    public String infoString;

    private CheckBox ck_isRemember;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        initView();
        //记住密码
        sp_readlog();
    }

    private void initView() {
        mBtnLogin = (TextView) findViewById(R.id.main_btn_login);
        main_btn_register = (TextView) findViewById(R.id.main_btn_register);
        getpassword = (TextView) findViewById(R.id.getpassword);
        ck_isRemember=(CheckBox)findViewById(R.id.ck_isRemember);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);

        progress = findViewById(R.id.layout_progress);
        mInputLayout = findViewById(R.id.input_layout);
        mName = (LinearLayout) findViewById(R.id.input_layout_name);
        mPsw = (LinearLayout) findViewById(R.id.input_layout_psw);

        mBtnLogin.setOnClickListener(this);
        main_btn_register.setOnClickListener(this);
        getpassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //case R.id.rb_tab1:
            //    mTabHost.setCurrentTabByTag("tab1");
            //    break;
            case R.id.main_btn_login:

//                mWidth = mBtnLogin.getMeasuredWidth();
//                mHeight = mBtnLogin.getMeasuredHeight();
//
//                mName.setVisibility(View.INVISIBLE);
//                mPsw.setVisibility(View.INVISIBLE);
//                LogUtil.e("---------main_btn_login----");
//                inputAnimator(mInputLayout, mWidth, mHeight);
                //设置提示框
                dialog = new ProgressDialog(LoginActivity.this);
                dialog.setTitle("正在登陆");
                dialog.setMessage("请稍后");
                dialog.setCancelable(false);//设置可以通过back键取消
                dialog.show();
                //设置子线程，分别进行Get和Post传输数据
                new Thread(new LoginThread()).start();
                LogUtil.e("---------end---main_btn_login----");
                break;
            case R.id.main_btn_register:

                LogUtil.e("---------main_btn_register----");
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.getpassword:

                LogUtil.e("---------getpassword----");
                Intent intent_getpassword = new Intent(LoginActivity.this,GetPassword.class);
                startActivity(intent_getpassword);
                break;
        }
    }
    public class LoginThread implements Runnable{
        @Override
        public void run() {
            String s_email = email.getText().toString();
            String s_password = password.getText().toString();
            LogUtil.e("s_email---------"+s_email);
            LogUtil.e("s_password---------"+s_password);
            if(s_email!=null  &&  s_password!=null  && s_email.length()>0 && s_password.length()>0){
                infoString = HttpUtil.httpget("loginuser?email="+s_email+"&password="+s_password);
                LogUtil.e("msgs---------"+infoString);
                //更新UI，使用runOnUiThread()方法
                showResponse(infoString);

            }else{
                new AlertDialog.Builder(LoginActivity.this)
                        .setTitle("提示信息")
                        .setMessage("邮箱或密码不能为空！")
                        .setPositiveButton("确定", null)
                        .show();

            }
        }
    }

    public void showResponse(final String response){
        runOnUiThread(new Runnable() {
            //更新UI
            @Override
            public void run() {
                //记住密码
                Boolean isRemember= ck_isRemember.isChecked();
                LogUtil.e("isRemember="+isRemember);
                LogUtil.e("infoString======"+infoString);
                if (isRemember){
                    sp_savelog();
                }else{
                    sp_clearlog();
                }
                dialog.dismiss();
                if(infoString!=null && !infoString.equals("")  && infoString.equals("\"ok\"")){
                    //跳转
                    Toast.makeText(LoginActivity.this,"登陆成功！", Toast.LENGTH_SHORT).show();
                    SysUtils.startActivity(LoginActivity.this, MainActivity.class);

                }else{
                    Toast.makeText(LoginActivity.this,"邮箱或密码不正确！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //记住密码
    private void sp_savelog() {
        //初始化
        SharedPreferences sp = getSharedPreferences(R.string.settings+"login", Context.MODE_PRIVATE);
        //k-v设置
        SharedPreferences.Editor editor = sp.edit();

        String sp_email=email.getText().toString();
        String password1=password.getText().toString();
        Boolean isRemember=ck_isRemember.isChecked();
        editor.putString("email",sp_email);
        editor.putString("password",password1);
        editor.putBoolean("isRemember", isRemember);
        //保存
        editor.apply();
    }
    //读取密码
    private void sp_readlog(){
        SharedPreferences sp=getSharedPreferences(R.string.settings+"login",Context.MODE_PRIVATE);
        String sp_email=sp.getString("email", "");
        String password1=sp.getString("password","");
        Boolean isRemember1=sp.getBoolean("isRemember",true);
        email.setText(sp_email+"");
        password.setText(password1+"");
        ck_isRemember.setChecked(isRemember1);
    }
    //清空密码
    private void sp_clearlog() {
        SharedPreferences sp=getSharedPreferences(R.string.settings+"login", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.clear();
        editor.apply();
    }

    private void inputAnimator(final View view, float w, float h) {
        AnimatorSet set = new AnimatorSet();
        ValueAnimator animator = ValueAnimator.ofFloat(0, w);
        animator.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                ViewGroup.MarginLayoutParams params = (MarginLayoutParams) view
                        .getLayoutParams();
                params.leftMargin = (int) value;
                params.rightMargin = (int) value;
                view.setLayoutParams(params);
            }
        });

        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout,
                "scaleX", 1f, 0.5f);
        set.setDuration(1000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator, animator2);
        set.start();
        set.addListener(new AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animator animation) {

                progress.setVisibility(View.VISIBLE);
                progressAnimator(progress);
                mInputLayout.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }
        });

    }

    private void progressAnimator(final View view) {
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                0.5f, 1f);
        PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                0.5f, 1f);
        ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(view,
                animator, animator2);
        animator3.setDuration(1000);
        animator3.setInterpolator(new JellyInterpolator());
        animator3.start();

    }

}
